package com.czm.cardgllery;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * 卡片滑动过程中  view的变化；以及一些滑动 轮播设置
 */
public class CardScaleHelper {
    private RecyclerView mRecyclerView;
    private Context mContext;

    private float mScale = 0.7f; // 两边视图scale
    private int mPagePadding = 15; // 卡片的padding, 卡片间的距离等于2倍的mPagePadding
    private int mShowLeftCardWidth = 35;   // 左边卡片显示大小

    private int mCardWidth; // 卡片宽度
    private int mOnePageWidth; // 滑动一页的距离
    private int mCardGalleryWidth;

    private int mCurrentItemPos; //当前所在索引
    private int mCurrentItemOffset;
    private int iItemCount = 0;
    private int carouselTime = 3000;
    private ICurrentItemChanged currentItemChanged;
    private boolean bCycle = false;
    private CardLinearSnapHelper mLinearSnapHelper = new CardLinearSnapHelper();

    public void attachToRecyclerView(final RecyclerView mRecyclerView) {
        this.mRecyclerView = mRecyclerView;
        mContext = mRecyclerView.getContext();
        iItemCount = mRecyclerView.getAdapter().getItemCount();
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    mLinearSnapHelper.mNoNeedToScroll = mCurrentItemOffset == 0 || mCurrentItemOffset == getDestItemOffset(iItemCount - 1);
                } else {
                    mLinearSnapHelper.mNoNeedToScroll = false;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // dx>0则表示右滑, dx<0表示左滑, dy<0表示上滑, dy>0表示下滑
                mCurrentItemOffset += dx;
                computeCurrentItemPos();
                onScrolledChangedCallback();
            }
        });

        initWidth();
        mLinearSnapHelper.attachToRecyclerView(mRecyclerView);
    }

    public void addCurrentItemChanged(ICurrentItemChanged currentItemChanged) {
        this.currentItemChanged = currentItemChanged;
    }

    private Handler handler = new Handler();

    /**
     * 轮播
     *
     * @param carouselTime 1秒=1000
     */
    public void Carousel(int carouselTime) {
        this.carouselTime=carouselTime;
        setcarouselTime(carouselTime);
        handler.postDelayed(mRunnable, carouselTime);
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            int iCurrentItemPos = getCurrentItemPos();
            if (iCurrentItemPos == iItemCount - 1)
                if (bCycle) {
                    mRecyclerView.smoothScrollToPosition(0);
                    handler.postDelayed(this, carouselTime);
                } else
                    handler.removeCallbacks(this);
            else {
                mRecyclerView.smoothScrollToPosition(++iCurrentItemPos);
                handler.postDelayed(this, carouselTime);
            }
        }
    };

    /**
     * 初始化卡片宽度
     */
    private void initWidth() {
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                mCardGalleryWidth = mRecyclerView.getWidth();
                mCardWidth = mCardGalleryWidth - ScreenUtil.dip2px(mContext, 2 * (mPagePadding + mShowLeftCardWidth));
                mOnePageWidth = mCardWidth;
                mRecyclerView.smoothScrollToPosition(mCurrentItemPos);
                if (currentItemChanged != null)
                    currentItemChanged.onCurrentItemChange(0);
                onScrolledChangedCallback();
            }
        });
    }

    /**
     * 设置轮播时间
     *
     * @param carouselTime 1秒=1000
     */
    private void setcarouselTime(int carouselTime) {
        this.carouselTime = carouselTime;
    }

    /**
     * 设置当前所在项
     *
     * @param currentItemPos 索引
     */
    public void setCurrentItemPos(int currentItemPos) {
        this.mCurrentItemPos = currentItemPos;
    }

    /**
     * 获取当前卡片索引
     *
     * @return 索引
     */
    public int getCurrentItemPos() {
        return mCurrentItemPos;
    }

    //计算RecyclerView到最后一项卡片宽度
    private int getDestItemOffset(int destPos) {
        return mOnePageWidth * destPos;
    }

    /**
     * 计算当前处于第几项card
     */
    private void computeCurrentItemPos() {
        if (mOnePageWidth <= 0) return;
        boolean pageChanged = false;
        // 滑动超过一页说明已翻页
        if (Math.abs(mCurrentItemOffset - mCurrentItemPos * mOnePageWidth) >= mOnePageWidth) {
            pageChanged = true;
            //移除3秒轮播
            // handler.removeCallbacks(mRunnable);
        }
        if (pageChanged) {
            mCurrentItemPos = mCurrentItemOffset / mOnePageWidth;
            if (currentItemChanged != null)
                currentItemChanged.onCurrentItemChange(mCurrentItemPos);
        }
    }

    /**
     * RecyclerView位移事件监听, view大小随位移事件变化
     */
    private void onScrolledChangedCallback() {
        //卡片位移的距离
        int offset = mCurrentItemOffset - mCurrentItemPos * mOnePageWidth;
        //位移距离和一张卡片宽度的 百分比，用于计算移动的时候卡片的大小变化
        float percent = (float) Math.max(Math.abs(offset) * (1.0 / mOnePageWidth), 0.0001);
        View leftView = null;
        View currentView;
        View rightView = null;
        if (mCurrentItemPos > 0) {
            leftView = mRecyclerView.getLayoutManager().findViewByPosition(mCurrentItemPos - 1);
        }
        currentView = mRecyclerView.getLayoutManager().findViewByPosition(mCurrentItemPos);
        if (mCurrentItemPos < mRecyclerView.getAdapter().getItemCount() - 1) {
            rightView = mRecyclerView.getLayoutManager().findViewByPosition(mCurrentItemPos + 1);
        }

        //percent越来越大   mScale不变
        if (leftView != null) {
            // y = (1 - mScale)x + mScale
            leftView.setScaleY((1 - mScale) * percent + mScale);
        }
        if (currentView != null) {
            // y = (mScale - 1)x + 1
            currentView.setScaleY((mScale - 1) * percent + 1);
        }
        if (rightView != null) {
            // y = (1 - mScale)x + mScale
            rightView.setScaleY((1 - mScale) * percent + mScale);
        }
    }

    /**
     * 设置2边试图的比例
     *
     * @param scale 比例
     */
    public void setScale(float scale) {
        mScale = scale;
    }

    /**
     * 卡片的padding, 卡片间的距离等于2倍的mPagePadding
     *
     * @param pagePadding 卡片的padding
     */
    public void setPagePadding(int pagePadding) {
        mPagePadding = pagePadding;
    }

    /**
     * 左边卡片显示大小
     *
     * @param showLeftCardWidth 左边卡片显示大小
     */
    public void setShowLeftCardWidth(int showLeftCardWidth) {
        mShowLeftCardWidth = showLeftCardWidth;
    }

    /**
     * 更新 card数量
     * @param iItemCount
     */
    public void updateItemCount(int iItemCount)
    {
        this.iItemCount=iItemCount;
    }
}
